<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增询价单')" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-quotation-add">
            <div class="form-group">
                <label class="col-sm-3 control-label">订单号：</label>
                <div class="col-sm-8">
                    <input name="billNo" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">订单时间：</label>
                <div class="col-sm-8">
                    <input name="billDate" id="billDate" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">订单主题：</label>
                <div class="col-sm-8">
                    <input name="subject" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">供应商：</label>
                <div class="col-sm-8">
                    <input name="supplierName" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">交货时间：</label>
                <div class="col-sm-8">
                    <input name="deliveryTime" id="deliveryTime" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">交货地点：</label>
                <div class="col-sm-8">
                    <input name="deliveryPlace" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">联系人：</label>
                <div class="col-sm-8">
                    <input name="contact" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">电话：</label>
                <div class="col-sm-8">
                    <input name="phone" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">email：</label>
                <div class="col-sm-8">
                    <input name="email" class="form-control" type="text">
                </div>
            </div>
            <div class="btn-group-sm pull-right"  role="group">
                <a class="btn btn-primary" onclick="saveQuotation()">
                    <i class="fa fa-edit"></i> 保存报价单
                </a>
            </div>
            <div class="row">
                <div class="col-sm-12 select-table table-striped">
                    <a class="btn btn-primary"  onclick="addData()">添加商品</a>
                    <table id="bootstrap-table"></table>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-table-editable-js" />
    <script th:inline="javascript">
        var prefix = ctx + "system/quotation"
        $("#form-quotation-add").validate({
            focusCleanup: true
        });
        $(function(){
            $("#deliveryTime").datetimepicker({
                format: "yyyy-mm-dd",
                minView: "month",
                autoclose: true
            });
            $("#billDate").datetimepicker({
                format: "yyyy-mm-dd",
                minView: "month",
                autoclose: true
            });

            var id = $("#id").val();
            if(id==null||id==''){
                id=0;
            }
            var options = {
                createUrl: prefix + "/add",
                url:   "detail/list?id="+id,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                showPageGo: false,
                pagination: false,
                onEditableSave: onEditableSave,
                columns: [{
                    checkbox: true
                },
                    {
                        field : 'productId',
                        title : '仓库商品明细ID',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='hidden' id='productCode%s' name='productCode' value='%s'>", index, value);
                            return html+value;
                        }
                    },
                    {
                        field : 'productCode',
                        title : '商品编码',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='hidden' id='productCode%s' name='productCode' value='%s'>", index, value);
                            return html+value;
                        }
                    },
                    {
                        field : 'productName',
                        title : '商品名称',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='hidden' id='productName%s' name='productName' value='%s'>", index, value);
                            return html+value;
                        }
                    },
                    {
                        field : 'productUnit',
                        title : '商品单位',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='hidden' id='productUnit%s' name='productUnit' value='%s'>", index, value);
                            return html+value;
                        }
                    },
                    {
                        field : 'productSpec',
                        title : '商品规格',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='hidden' id='productSpec%s' name='productSpec' value='%s'>", index,index, value);
                            return html+value;
                        }
                    },
                    {
                        field : 'productCount',
                        title : '数量',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='productCount' name='productCount' value='%s'>", index, value);
                            return html;
                        }
                    },
                    {
                        field : 'price',
                        title : '价格',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='price%s' name='price' value='%s'>", index, value);
                            return html;
                        }

                    },
                    {
                        field : 'taxRate',
                        title : '税率%',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='taxRate%s' name='taxRate' value='%s'>", index, value);
                            return html;
                        }
                    },{
                        field : 'discountRate',
                        title : '折扣',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='discountRate%s' name='discountRate' value='%s'>", index, value);
                            return html;
                        }
                    },{
                        field : 'amt',
                        title : '含税金额',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='amt%s' name='amt' value='%s'>", index, value);
                            return html;
                        }
                    },
                    {
                        field: 'remark',
                        title: '备注',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='remark%s' name='remark' value='%s'>", index, value);
                            return html;
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        formatter: function(value, row, index) {
                            var actions = [];
                            actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeData(\'' + index + '\')"><i class="fa fa-remove"></i>删除</a>');
                            return actions.join('');
                        }
                    }]
            };
            $.table.init(options);





        })

        function onEditableSave (field, row, rowIndex, oldValue, $el) {

            // alert("字段名：" + field + "，当前值：" + row[field]  + "，旧值：" + oldValue);

        }


        function saveQuotation(){

            if ($.validate.form()) {
                let datajson = classformToJson($('.form-control'));
                datajson['id']=0;

                //var productData = getData();

                var QuotationData = [];
                $("#" + table.options.id+" tbody tr").each(function (){
                    var quotation = {}
                    $(this).find(".form-control").each(function (){
                        var n, v;
                        n = $(this).attr("name");
                        v = $(this).val();
                        quotation[n] = v;
                    })
                    QuotationData.push(quotation);
                })
                if(QuotationData.length==0){
                    $.modal.alertError("请录入询价商品");
                    return;
                }
                for (let i = 0; i <QuotationData.length ; i++) {
                    var product = QuotationData[i];
                    var productName = product.productName;
                    var productCount = product.productCount;
                    var price = product.price;
                    var c = i+1;
                    if(productName==null||productName==undefined||productName==""){
                        $.modal.alertError("第("+c+")请输入询价商品名称");
                        return ;
                    }
                    if(productCount==null||productCount==undefined||productCount==""){
                        $.modal.alertError("第("+c+")请输入询价商品数量");
                        return ;
                    }
                    if(isNotBlank(price)){
                        $.modal.alertError("第("+c+")请输入询价商品单价");
                        return ;
                    }
                    if(isNotBlank(price)){
                        $.modal.alertError("第("+c+")请输入询价商品数量");
                        return ;
                    }
                    if(isNotBlank(product.taxRate)){
                        $.modal.alertError("第("+c+")请输入询价商品税率");
                        return ;
                    }
                    if(isNotBlank(product.discountRate)){
                        $.modal.alertError("第("+c+")请输入询价商品折扣");
                        return ;
                    }
                    if(isNotBlank(product.amt)){
                        $.modal.alertError("第("+c+")请输入询价商品含税金额");
                        return ;
                    }
                }
                datajson['list']=QuotationData;
                //var data = $("#form-in-add").serializeArray();
                var config = {
                    url: prefix+"/add",
                    type: "post",
                    data: JSON.stringify(datajson),
                    contentType:"application/json",
                    beforeSend: function () {
                        $.modal.loading("正在处理中，请稍候...");
                    },
                    success: function(result) {
                        if(result.code==0){
                            $.modal.alertSuccess("保存成功");
                            $.modal.closeTab();
                        }else{
                            $.modal.alertError(result.msg);
                        }
                        console.log(result);
                    }
                };
                $.ajax(config);
                //$.operate.save(prefix + "/add", data);
            }
        }

        function  isNotBlank(value){
            if(value==null||value==undefined||value==""){

            }
            return false;
        }

        /* 查询表格所有数据值 */
        function getData(){
            var data = $("#" + table.options.id).bootstrapTable('getData');
            // alert(JSON.stringify(data))
            return data;
        }

        function adddetail(){
            var newRow =  {
                "supplyQuotationId": 0,
                "productId": 0,
                "productCode": "",
                "productName": "",
                "productUnit": "",
                "productSpec": "",
                "productCount": 0,
                "price": "",
                "remark": "",
                "taxRate": "",
                "discountRate": "",
                "amt": ""
            }
            $("#" + table.options.id).bootstrapTable('append',newRow);
        }
        function addStashProduct(productData) {


            var newRow = {
                stashProductId: productData.id,
                productCode: productData.productCode,
                productName: productData.productName,
                stashName: productData.stashName,
                productUnit: productData.productUnit,
                productSpec: productData.productSpec,
                availableCount: productData.availableCount,
                outCount: productData.outCount,
                outStashAmount: productData.outStashAmount,
                settleAmount: productData.settleAmount,
                remark: '请点击输入',
            };
            $("#" + table.options.id).bootstrapTable('append',newRow);

        }

        function classformToJson(form) {
            var jsonObj = {};
            form.each(function (){
                let val = $(this).val();
                let name = $(this).attr('name');
                jsonObj[name] = val;
            })
            return jsonObj;
        }
        function removeData(index){

            var data = $("#" + table.options.id).bootstrapTable('getData');
            data.splice(index, 1);

            $("#" + table.options.id).bootstrapTable('load', data);

        }

        function addData(){
            // $.modal.closeTab();

            $.operate.selectProduct("/scm/product/popupListPage",selectProductCallback);

            // $("#" + table.options.id).bootstrapTable('append',newRow);

        }

        function selectProductCallback(productId) {

            console.log("selectProductCallback"+productId);

            var config = {
                url: ctx+"scm/product/detail/"+productId,
                type: "post",
                dataType: "json",
                data: null,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                },
                success: function(result) {

                    console.log(result);
                    console.log(result.data);

                    addProduct(result.data);
                    $.modal.closeLoading();
                }
            };
            $.ajax(config);

        }

        function addProduct(productData){
            var count = $("#" + table.options.id).bootstrapTable('getData').length;

            var newRow =  {
                index: $.table.serialNumber(count),
                "supplyQuotationId": 0,
                "productId": productData.id,
                "productCode": productData.productCode,
                "productName": productData.productName,
                "productUnit": productData.productUnit,
                "productSpec": "",
                "productCount": 0,
                "price": "",
                "remark": "",
                "taxRate": "",
                "discountRate": "",
                "amt": ""
            }
           /* var newRow = {
                index: $.table.serialNumber(count),
                productId: productData.id,
                productCode: productData.productCode,
                productName: productData.productName,
                productUnit: productData.productUnit,
                productCount: '',
                remark: '',
            };*/
            sub.addRow(newRow);
        }

    </script>
</body>
</html>
